package com.bw.demo.controller;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotBlank;

import org.hibernate.validator.HibernateValidator;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.bw.demo.model.BwResult;
import com.bw.demo.model.Course;
import com.bw.demo.model.UserDto;

/**
 * 
 */
@Validated 
@RestController
@RequestMapping("/test")
public class UserController 
{
	
	/********************  方式一：纯注解模式  *************************/
	
	// 校验不通过，抛出org.springframework.web.bind.MethodArgumentNotValidException
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public BwResult save(@Validated @RequestBody UserDto user) 
	{
		return BwResult.success().setData(user);
	}
	
	// 校验不通过，抛出org.springframework.validation.BindException
	@RequestMapping(value = "save", method = RequestMethod.GET)
	public BwResult save(@Validated Course user) 
	{
		return BwResult.success().setData(user);
	}
	
	// 校验不通过，抛出javax.validation.ConstraintViolationException 
	@RequestMapping(value = "get", method = RequestMethod.POST)
	public BwResult getPost(@NotBlank(message = "id不能为空") String id) 
	{
		return BwResult.success().setData(id);
	}
	
	// 校验不通过，抛出javax.validation.ConstraintViolationException 
	@RequestMapping(value = "get", method = RequestMethod.GET)
	public BwResult get(@NotBlank(message = "id不能为空") String id) 
	{
		return BwResult.success().setData(id);
	}
	
	/**************************  方式二：BindingResult接收校验结果  ***********************/
	
	@RequestMapping(value = "save2", method = RequestMethod.POST)
	public BwResult save2(@Validated @RequestBody UserDto user, BindingResult result) 
	{
		if (result.hasErrors()) 
		{
			throw new RuntimeException("参数校验失败");
		}
		return BwResult.success().setData(user);
	}
	
	/*************************  方式三：手动校验模式  ************************/
	
	@RequestMapping(value = "save3", method = RequestMethod.POST)
	public BwResult save3(@RequestBody UserDto user) 
	{
		// 构建校验器， failFast-true:快速失败
		Validator validator = Validation.byProvider(HibernateValidator.class).configure()
			.failFast(false).buildValidatorFactory().getValidator();
		// 校验
		Set<ConstraintViolation<UserDto>> validResult = validator.validate(user);
		if (validResult.size() > 0) 
		{
			throw new RuntimeException("参数校验失败");
			/*
			 * for (ConstraintViolation<UserDto> constraintViolation : validResult) 
			 * { 
			 * 	String message = constraintViolation.getMessage();
			 * }
			 */
		}
		return BwResult.success().setData(user);
	}
	
}
